package com.panda.pandawash.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.panda.pandawash.bean.HttpResultBean;
import com.panda.pandawash.R;
import com.panda.pandawash.application.CDApplication;
import com.panda.pandawash.bean.UserBean;
import com.panda.pandawash.util.CDPreferenceOperateUtils;
import com.panda.pandawash.util.HttpUtil;
import com.panda.pandawash.util.WsUtils;
import com.panda.pandawash.view.LoadingDialog;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

@ContentView(R.layout.activity_main)
public class LoginActivity extends Activity  {
    private static String TAG = "API_TAG";
    @ViewInject(R.id.btn_login)
    private Button userloginButton;

    @ViewInject(R.id.edit_user_name)
    private EditText mUsernameTextView;

    @ViewInject(R.id.edit_login_passwd)
    private EditText userPasswordEditText;

    @ViewInject(R.id.btn_register)
    private TextView newUserButton;

    @ViewInject(R.id.btn_forget_psw)
    private TextView userProblembButton;

    private LoadingDialog dialog;
    private String account;
    private String passwd;
    private String registerpassword;
    private String registerusername;
    private UserBean user;
    //临时保存用户名等信息

    private CDPreferenceOperateUtils mPreference;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        }
        initRes();

    }
    private void initRes(){
        user = CDApplication.getIntance().getUserInfo();
        if(user.getUseraccount() != null){
            mUsernameTextView.setText(user.getUseraccount());
        }
        userPasswordEditText.addTextChangedListener(watcher);
        registerusername = mUsernameTextView.getText().toString().trim();
        registerpassword = userPasswordEditText.getText().toString().trim();
        if (registerusername.length() > 0 && registerpassword.length() > 0) {
            userloginButton.setBackgroundResource(R.drawable.ic_register_btn);
            userloginButton.setTextColor(0xffffffff);
            userloginButton.setClickable(true);
        } else {
            userloginButton.setBackgroundResource(R.drawable.ic_btn_disable);
            userloginButton.setTextColor(0x80ffffff);
            userloginButton.setClickable(false);
        }

    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Event(R.id.btn_login)
    private void login(View view) {
        if(isValidLoginInfo()) {
            dialog = new LoadingDialog(this, "正在登录.....");
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
            HttpUtil.login(new LoginCallback(),account,account,passwd);
        }
    }

    @Event(R.id.btn_forget_psw)
    private void forgetPsw(View view) {
        Intent mIntent = new Intent(LoginActivity.this, ForgetPswdActivity.class);
        startActivity(mIntent);
    }

    @Event(R.id.btn_register)
    private void register(View view){
        Intent mIntent = new Intent(LoginActivity.this, RegisterActivity.class);
        startActivity(mIntent);
        finish();
    }


    private boolean isValidLoginInfo(){
        account = mUsernameTextView.getText().toString().trim();
        if (TextUtils.isEmpty(account)) {
            showMessage("请输入用户名/手机号");
            mUsernameTextView.requestFocus();
            return false;
        }
        if (!WsUtils.isPhoneNumber(account)) {
            showMessage("请输入正确的手机号码");
            mUsernameTextView.requestFocus();
            return false;
        }
        passwd = userPasswordEditText.getText().toString().trim();
        if (TextUtils.isEmpty(passwd)) {
            showMessage("请输入密码");
            userPasswordEditText.requestFocus();
            return false;
        }
        return true;

    }

    private void showMessage(String string) {
        Toast toast = Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    private TextWatcher watcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub


        }

        @Override
        public void afterTextChanged(Editable s) {

            if (s.toString().length() > 0) {
                userloginButton.setBackgroundResource(R.drawable.ic_register_btn);
                userloginButton.setClickable(true);
                userloginButton.setTextColor(0xffffffff);
            } else {
                userloginButton.setBackgroundResource(R.drawable.ic_btn_disable);;
                userloginButton.setClickable(false);
                userloginButton.setTextColor(0x88ffffff);
            }

        }
    };

    private class LoginCallback extends AsyncHttpResponseHandler {
        @Override
        public void onSuccess(int statusCode, String content) {
            super.onSuccess(statusCode, content);
            Log.d(TAG, "LoginCallback statusCode = " + statusCode);
            Log.d(TAG, "LoginCallback onSuccess = " + content);
            if (statusCode == 200) {
                HttpResultBean resultBean = HttpUtil.parserHttpResultInfo(content, "user");
                Log.d(TAG, "resultBean = " + resultBean);
                if (resultBean != null) {
                    String code = resultBean.getCode();
                    String message = resultBean.getMessage();
                    Log.d(TAG, "code = " + code);
                    if(code.equals("0")){
                        dialog.cancel();
                        userloginButton.setClickable(false);
                        loginSuccess();
                        showMessage(getString(R.string.login_success));
                    }else if(code.equals("99")){
                        dialog.cancel();
                        userloginButton.setClickable(true);
                        showMessage(message);

                    }
                }
            } else {
                showMessage(getString(R.string.login_fail));
            }
        }
    }

    private void loginSuccess(){
        CDApplication.getIntance().setLoginStatus(true);
        user.setUseraccount(account);
        user.setUserpassword(passwd);
        CDApplication.getIntance().saveUserInfo(user);
        Intent mIntent = new Intent(LoginActivity.this, PandaWashActivity.class);
        LoginActivity.this.startActivity(mIntent);
        LoginActivity.this.finish();
    }

}
